import random
import re
from flask import current_app
from flask import make_response, jsonify
from flask import request
from flask import session

from focus_dir import redis_store, db
from focus_dir.constants import IMAGE_CODE_REDIS_EXPIRES, SMS_CODE_REDIS_EXPIRES
from focus_dir.models import User
from utils.captcha.captcha import captcha
from utils.response_code import RET
from utils.yuntongxun.sms import CCP
from . import passport_blu


@passport_blu.route("/image_code")
def get_image_code():
    """生成图片验证码"""
    # 获取浏览器随机生成的uuid
    image_code_id = request.args.get("image_code_id")

    if not image_code_id:
        return jsonify(errno=RET.PARAMERR, errmsg="缺少参数")
    # 生成图片验证码
    name, text, content = captcha.generate_captcha()

    # 将图片验证码保存到redis仓库（键'image_code:'+image_code_id 值 text）
    try:
        redis_store.set("image_code:" + image_code_id, text, IMAGE_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存图片验证码失败")

    # 设置返回对象
    response = make_response(content)
    # 修改Content-Type为图片类型
    response.headers["Content-Type"] = "image/jpg"

    # 返回响应体
    return response


@passport_blu.route("/sms_code", methods=["POST"])
def sms_code():
    """短信验证"""
    # 获取参数
    data_dict = request.json
    mobile = data_dict.get("mobile")
    image_code = data_dict.get("image_code")
    image_code_id = data_dict.get("image_code_id")
    # 校验参数完整性
    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.DATAERR, errmsg="缺少参数")
    if not re.match(r"^1[3568]\d{9}$", mobile):
        return jsonify(errno=RET.DATAERR, errmsg="手机格式错误")

    # 查找数据库并检验用户输入是否正确
    try:
        red_image_code = redis_store.get("image_code:" + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询图片验证码出错")

    if not red_image_code:
        return jsonify(errno=RET.NODATA, errmsg="图片验证码过期")

    if image_code.lower() != red_image_code.decode().lower():
        return jsonify(errno=RET.DATAERR, errmsg="输入验证码错误")
    try:  # 查询手机是否已被注册
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")
    if user:  # 如果存在表示已经注册
        return jsonify(errno=RET.DATAEXIST, errmsg="该手机已经被注册")

    # 生成短信验证码并发送短信验证
    auth_code = random.randint(0, 999999)
    auth_code = "%06d" % auth_code
    # ccp = CCP()
    # result = ccp.send_template_sms(mobile, [sms_code, 5], 1)
    # if result != 0:
    #     return jsonify(errno=RET.THIRDERR, errmsg="发送短信失败")

    # 保存短信验证码到redis仓库键"auth_code:"+mobile，值auth_code
    try:
        redis_store.set("auth_code:" + mobile, auth_code, SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存验证码失败")

    # 返回发送验证码成功
    return jsonify(errno=RET.OK, errmsg="发送成功")


@passport_blu.route("/register", methods=["POST"])
def register():
    """用户注册"""
    # 获取参数

    data_dict = request.json
    mobile = data_dict.get("mobile")
    sms_code = data_dict.get("sms_code")
    password = data_dict.get("password")
    agree = data_dict.get("agree")

    # 查询校验参数
    if not all([mobile, sms_code, password, agree]):
        return jsonify(errno=RET.DATAERR, errmsg="缺少参数")

    if not re.match(r"^1[3568]\d{9}$", mobile):
        return jsonify(errno=RET.DATAERR, errmsg="手机格式错误")

    try:  # 查询手机是否已被注册
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")
    if user:  # 如果存在表示已经注册
        return jsonify(errno=RET.DATAEXIST, errmsg="该手机已经被注册")

    # 查询redis数据库保存的短信验证码
    try:
        re_sms_code = redis_store.get("auth_code:" + mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询短信验证码失败")
    if not re_sms_code:
        return jsonify(errno=RET.NODATA, errmsg="短信验证码过期")

    if sms_code != re_sms_code.decode():
        return jsonify(errno=RET.DATAERR, errmsg="输入验证码错误")

    # 删除短信验证码
    try:
        redis_store.delete("SMS_" + mobile)
    except Exception as e:
        current_app.logger.error(e)

    # 保存用户数据
    user = User()
    user.mobile = mobile
    user.nick_name = mobile
    user.password = password
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库操作失败")

    # 保存用户登录状态(为了注册后能够直接登录页面)
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile

    # 返回注册成功
    return jsonify(errno=RET.OK, errmsg="注册成功")


@passport_blu.route("/login", methods=["POST"])
def login():
    """登陆验证"""
    # 获取参数，判断完整性
    data_dict = request.json
    mobile = data_dict.get("mobile")
    password = data_dict.get("password")
    if not all([mobile, password]):
        return jsonify(errno=RET.DATAERR, errmsg="缺少参数")
    # 查询手机号判断是否注册
    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")
    if not user:
        return jsonify(errno=RET.DATAEXIST, errmsg="该手机未注册")

    # 校验用户收入密码是否正确
    if not user.check_passowrd(password):
        return jsonify(errno=RET.DATAERR, errmsg="密码输入错误")

    # 状态保持
    session["mobile"] = user.mobile
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name

    # 返回登陆成功

    return jsonify(errno=RET.OK, errmsg="OK")
